<template>
	<view class="device-param-setting">
		<site-basic-cell :name="siteName"></site-basic-cell>
		<up-cell-group class="setting-form" :border="false">
			<up-cell :title="$t('device.param.setting.cell-1')">
				<template #value>
					<up-input v-model.number="formData.highSOC" border="none" type="digit" inputAlign="right"
						:placeholder="$t('device.param.setting.cell-1.placeholder')"></up-input>
				</template>
			</up-cell>
			<up-cell :title="$t('device.param.setting.cell-2')">
				<template #value>
					<up-input v-model.number="formData.lowSOC" border="none" type="digit" inputAlign="right"
						:placeholder="$t('device.param.setting.cell-2.placeholder')"></up-input>
				</template>
			</up-cell>
		</up-cell-group>

		<publish-footer :beforePublish="beforePublish" @publish="handlePublish"></publish-footer>
	</view>
</template>

<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		reactive,
		ref,
		watch
	} from "vue";
	import {
		selectDeviceParameter,
		setDeviceParameter
	} from "@/apis/components/siteSet";
	import {
		useI18n
	} from "vue-i18n";

	const {
		t
	} = useI18n();

	const siteName = ref(null);
	const siteId = ref(null);
	const formData = reactive({
		highSOC: "",
		lowSOC: "",
		siteId: ""
	})
	onLoad(({
		name,
		id
	}) => {
		siteName.value = name;
		siteId.value = id;
		formData.siteId = id;
	})

	const verifyFields = () => {
		if (!formData.highSOC) {
			return t('device.param.setting.cell-1.placeholder');
		} else if (!formData.lowSOC) {
			return t('device.param.setting.cell-2.placeholder');
		} else if (formData.highSOC < 0 || formData.highSOC > 100 || formData.lowSOC < 0 || formData.lowSOC > 100) {
			return t('device.param.setting.warn-1');
		} else if (formData.highSOC <= formData.lowSOC) {
			return t('device.param.setting.warn-2');
		}
		return null;
	}
	const beforePublish = () => {
		const message = verifyFields();
		if (message) {
			uni.showToast({
				icon: 'none',
				title: message
			})
			return false;
		}
		return true;
	}
	const handlePublish = async () => {
		try {
			await setDeviceParameter(formData);
			uni.navigateBack()
			uni.$u.toast(t('site.parameter.settings.publish.successful'))
		} catch (err) {
			uni.$u.toast(typeof err === "string" ? err : err.message)
		}
	}

	const loadData = async () => {
		const {data} = await selectDeviceParameter(siteId.value);
		Object.keys(data || {}).forEach(key => {
			if(key !== 'siteId'){
				formData[key] = data[key] || "";
			}
		})
	}

	watch(() => siteId.value, now => {
		if (now) {
			loadData();
		}
	}, {
		immediate: true
	})
</script>

<style lang="scss">
	.device-param-setting {
		padding: 24rpx 32rpx;

		.setting-form {
			margin-top: 24rpx;
		}
	}
</style>